#!/usr/bin/env node

/*
 * genjwk - generate keypair then save them as RFC 7517 JSON Web Key(JWK) files.
 *
 * Copyright (c) 2016 Kenji Urushima (kenji.urushima@gmail.com)
 *
 * This software is licensed under the terms of the MIT License.
 * https://kjur.github.io/jsrsasign/license
 *
 * The above copyright and license notice shall be 
 * included in all copies or substantial portions of the Software.
 * 
 * Please use '-h' option for this script usage.
 * ---------------------------------------------------------
 * DESCRIPTION
 *   This script generates RSA or EC public key pair, then
 *   plain RFC 7517 JSON Web Key(JWK) format.
 *   - JWK private key
 *   - JWK public key
 *
 * USAGE
 *   Genearte yyy.{pub.jwk,prv.jwk} for EC P-256.
 *   % genjwk EC P-256 yyy
 *   Genearte xxx.{pub.jwk,prv.jwk} for RSA 2048bit
 *   % genjwk RSA 2048 xxx
 */

var program = require('commander');
var rs = require('jsrsasign');
var rsu = require('jsrsasign-util');
var path = require('path');

program
  .version('1.0.1 (2016-Sep-11)')
  .description('generate keypair, then save them as JWK files')
  .usage('[options] [RSA|EC] [RSASIZE|CURVE] [file head]')
  .parse(process.argv);

//console.log("program.args.length=" + program.args.length);

if (program.args.length !== 3)
  throw "wrong number of args"

var keyalg = program.args[0];
var keyopt = program.args[1];
var head = program.args[2];

var pubFile = head + ".pub.jwk";
var prvFile = head + ".prv.jwk";

console.log("generating keypair...");
var kp = rs.KEYUTIL.generateKeypair(keyalg, keyopt);
console.log("keypair generated...");
var prvKey = kp.prvKeyObj;
var pubKey = kp.pubKeyObj;
var prvJWK = rs.KEYUTIL.getJWKFromKey(prvKey);
var pubJWK = rs.KEYUTIL.getJWKFromKey(pubKey);

rsu.saveFile(pubFile, JSON.stringify(pubJWK, null, 2));
rsu.saveFile(prvFile, JSON.stringify(prvJWK, null, 2));

console.log("all save done.");

